import React, { useState, useEffect, useRef } from 'react';
import { DatePicker,Button, Form, Input, Select, Col, Row, Tooltip, Table, Pagination, Modal, Radio, message, Upload, Spin  } from 'antd';

import { SyncOutlined, SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined, VerticalAlignBottomOutlined, InboxOutlined, EyeOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { getListAPI, delAPI, getDetailAPI, addAPI, addBatchAPI, putAPI, uploadIniAPI } from '@/api/modules/equipment/jiaoyantable';
import { getDictsApi } from '@/api/modules/system/dictData';
import { download } from '@/api';
import { pageDelJump ,downloadJSON} from '@/utils';
import { IjiaoyantableType, IjiaoyantableDetailType, IjiaoyantableShenHeType } from '@/type/modules/equipment/jiaoyantable';
import ColorBtn from '@/components/ColorBtn';
import { hasPermi } from '@/utils/auth';
import { IdictType } from '@/type/modules/system/sysDictData';
import useStore from '@/store';
import { getListAPI as getDeptListApi } from '@/api/modules/system/dept';
import { IdeptType, ITreeType } from '@/type/modules/system/dept';
import { generalTreeFn, getChildrenById } from '@/utils/tree';
import { ipcApiRoute } from '@/api/main';
import { ipc } from '@/utils/ipcRenderer';
import './index.scss';
import { checkFiles, parseFiles,startLimit,calculateHash } from '@/utils/formats.js';
import { getAllListAPI as getAllListAPI_jiaoyanguize } from '@/api/modules/equipment/jiaoyanguize';
import { GongzuoleixingTable2Radios, gongzuoleixingList } from '../gongzuoleixing';
import { jiaoyanguizeList } from '../jiaoyanguize';
import { shebeiList } from '../shebei';
import { shebeifenzuList, ShebeifenzuTableSelect } from '../shebeifenzu';
import { shebeileixingList } from '../shebeileixing';
import { LocalCheckCom } from './localCheck';

const { RangePicker } = DatePicker;
const { Dragger } = Upload;
const JiaoyanjieguoTable = () => {
    const { TextArea } = Input;
    const [queryForm] = Form.useForm();
    const [addEditForm] = Form.useForm();
    const { confirm } = Modal;
    const {
        useUserStore: { userInfo, setUserInfo },
        useLayoutStore: { defaultObjMobx, changeTabsListMobx },
    } = useStore();
    // 分页
    const [queryParams, setQueryParams] = useState<IjiaoyantableType>({ pageNum: 1, pageSize: 10 });
    // 列表数据
    const [dataList, setDataList] = useState({ count: 0, rows: [] as IjiaoyantableDetailType[] });
    // table loading
    const [loading, setLoading] = useState(true);
    // 新增编辑 model显隐
    const [isModalOpen, setIsModalOpen] = useState(false);
    // 新增编辑判断
    const [isAdd, setIsAdd] = useState(true);
    // 非单个禁用
    const [single, setSingle] = useState(true);
    // 非多个禁用
    const [multiple, setMultiple] = useState(true);
    // 保存table 选择的key
    const [selectKeys, setSelectKeys] = useState<React.Key[]>([]);
    //  table 后台使用的key
    const [rowKeys, setRowKeys] = useState('');
    // 控制搜索隐藏显示
    const [searchShow, setSearchShow] = useState(true);
    // 当前编辑的id
    const [currentId, setCurrentId] = useState<number>();
    // 站列表,可以通过站列表长度大于1判断是不是省长
    const [deptArr, deptArrSet] = useState<any>([]);
    // 文件上传
    const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
    // 文件上传
    const [checkModalOpen, setcheckModalOpen] = useState(false);
    // 下载校验规则数据到客户端按钮loading
    const [syncDataFromServerLoading, syncDataFromServerLoadingSet] = useState(false);
    // 上传按钮loading
    const [uploadLoading, uploadLoadingSet] = useState(false);
    // 文件上传 判断是否更新用户数据
    const [isUpdateSupport, setIsUpdateSupport] = useState('0');
    // 存储已上传的文件
    const [isFiles, setIsFiles] = useState<UploadFile<any>[]>([]);
    const hookThis = useRef<any>({ localCheckCom: null });

    // 详情页数据
    const [detail, detailSet] = useState<any>({ jiaoyanjieguo: [] });
    const [lixianshuju, lixianshujuSet] = useState<any>([]);
    const [checkResultRemarks, checkResultRemarksSet] = useState<any>('');
    const [workTypeValue, workTypeValueSet] = useState<any>('');
    const [isZhanZhang, isZhanZhangSet] = useState<any>(true);
    const [localCheckDataModalOpen, localCheckDataModalOpenSet] = useState<any>(false);
    const [deptId, deptIdSet] = useState<any>('');
    useEffect(() => {
        try {
            const getDictsFn = async () => { };
            getDictsFn();
            // 获取用户站id
            const deptId = userInfo?.dept?.deptId;
            const deptName = userInfo?.dept?.deptName;
            const initFn = async () => {
                // 获取整个站数据
                const { data } = await getDeptListApi();
                data.result.rows.sort((a, b) => {
                    const a1 = a.orderNum as number;
                    const b1 = b.orderNum as number;
                    return a1 - b1;
                });
                // 通过generalTreeFn给叶子节点加上isleaf属性
                const treeData = generalTreeFn(data.result.rows, 'parentId', 'deptId') as ITreeType[];
                const allChildNodes = getChildrenById(data.result.rows, deptId).filter((item: any) => item.isleaf);
                if (allChildNodes.length > 0) {
                    // 有叶子节点说明是省长
                    isZhanZhangSet(false);
                }
                const isleafNode = data.result.rows.find((item: any) => item?.deptId === deptId)?.isleaf;
                if (isleafNode) {
                    // 将站长本身节点加入下拉选项中
                    allChildNodes.push({
                        deptId,
                        deptName,
                    });
                }

                deptArrSet(allChildNodes);
                queryForm.setFieldsValue({
                    deptId: allChildNodes[0]?.deptId,
                });
                searchQueryFn();
            };
            initFn();
        } catch (error) { }
    }, [userInfo?.dept?.deptId]);
    // excel 导入
    const props: UploadProps = {
        name: 'file',
        multiple: true,
        accept: '.ini,.bkp',
        fileList: isFiles,
        // maxCount:5,
        beforeUpload: () => false,
        onChange: (info) => {
            setIsFiles(info.fileList);
        },
    };
    const handleUploadOk = async () => {
        if (!workTypeValue) {
            message.warn('请选择工作类型');
            return;
        }
        const fileTypeSet = new Set<string>();
        try {
            const cur_dept_id = queryForm.getFieldValue('deptId');
            const deviceNameArr: any = []
            isFiles.forEach((file: any) => {
                const nameSplit = file.name.split('.')
                const houzhui = nameSplit[nameSplit.length - 1]
                fileTypeSet.add(houzhui);
                let fileName = file.name
                fileName = fileName.replace(/\s/g, '')
                deviceNameArr.push(fileName)
            });
            if (fileTypeSet.size > 1) {
                return message.warn('文件类型不一致');
            }
            // const { data } = await uploadIniAPI(fd);
            // message.success(data.message);
            const emptyRuleDevice: any = {}
            deviceNameArr.forEach((item: any) => {
                emptyRuleDevice[item] = true
            })
            const fileRules: any = await getAllListAPI_jiaoyanguize({ work_type: workTypeValue, deviceNameArr })
            const { data: { result } } = fileRules
            result.forEach((item: any) => {
                emptyRuleDevice[item.deviceName] = false
            })
            
            const epmtyRuleDeviceArr = Object.keys(emptyRuleDevice).filter((item: any) => emptyRuleDevice[item])
            if (epmtyRuleDeviceArr.length > 0) {
                return message.warn(`上传文件中，${epmtyRuleDeviceArr.join(',')}没有对应校验规则，请到【设备管理】增加设备和校验规则`)
            }
            const addItems: any = []
            uploadLoadingSet(true);
            Promise.all(isFiles.map((file: any) => new Promise<void>(async (resolve) => {
                const { originFileObj } = file
                let fileName = originFileObj.name
                const new_filename = await calculateHash(originFileObj)
                // console.log(`new_filename`,new_filename)
                fileName = fileName.replace(/\s/g, '')
                const reader = new FileReader();
                reader.onload = function (e: any) {
                    const fileContent = e.target.result;
                    // 文件内容
                    const resultData = parseFiles(fileContent, fileName);
                    // 当前文件的校验规则
                    const currentfileRules = fileRules.data.result.filter((item: any) => item.deviceName === fileName && item.workType === workTypeValue)
                    const jiaoyanjieguo = checkFiles(resultData, currentfileRules)
                    const { checkData, checkStatus } = jiaoyanjieguo;
                    const check_result_status = checkStatus === '0' ? '1' : '0';
                    /* 
                    check_result
                              '0':'待审核',
                              '1':'自动审核通过',
                              '2':'省长审核通过',
                              '3':'省长审核不通过',
                    */
                    addItems.push({
                        filepath: 'file.filepath',
                        original_filename: fileName,
                        new_filename, // 文件校验码
                        jiaoyanjieguo: JSON.stringify(jiaoyanjieguo),
                        check_result: check_result_status, // 审核结果状态
                        dept_id: cur_dept_id,
                    })
                    resolve()
                };
                reader.readAsText(originFileObj);
            }))).then(() => {
                addItems.forEach((item:any,index:number) => {
                    addItems[index] = [item]
                })
                // 分多次调用接口
                startLimit(addItems, addBatchAPI, 5, (res) => {
                    message.success('上传成功');
                    setIsUploadModalOpen(false);
                    setIsUpdateSupport('0');
                    setIsFiles([]);
                    getList();
                    uploadLoadingSet(false);
                }) 
            })
        } catch (error) { 
            uploadLoadingSet(false);
        }
    };
    const handleUploadCancel = () => {
        setIsUploadModalOpen(false);
        setIsFiles([]);
        setIsUpdateSupport('0');
    };
    const handleCheckOk = async (check_result: string) => {
        try {
            const values = { check_result, check_result_remarks: checkResultRemarks, check_user_id: userInfo.userName };
            await putAPI({ ...values, tableId: currentId });
            message.success('操作成功');
            setcheckModalOpen(false);
            getList();
        } catch (error) { }
    };
    const handleCheckCancel = () => {
        setcheckModalOpen(false);
        setIsFiles([]);
    };

    // 查询列表
    const getList = async () => {
        try {
            if (queryParams?.deptId) {
                const { data } = await getListAPI(queryParams);
                setDataList({ ...data.result });

                message.success('查询成功');
                setLoading(false);
            } else {
                setLoading(false);
            }
        } catch (error) { 
        }
    };

    useEffect(() => {
        getList();
    }, [queryParams]);

    // 搜索
    const searchQueryFn = () => {
        const form = queryForm.getFieldsValue();
        if (form.createTimeDuration) {
            form.createTimeDuration = form.createTimeDuration.map(item => item.format('YYYY-MM-DD HH:mm:ss')).join(',');
        }
        setQueryParams({
            pageNum: 1,
            pageSize: 10,
            ...form,
        });
    };

    // 重置
    const resetQueryFn = () => {
        queryForm.resetFields();
        setSelectKeys([]);
        setQueryParams({ pageNum: 1, pageSize: 10 });
    };

    // row-select
    const rowSelection = {
        selectedRowKeys: selectKeys,
        onChange: (selectedRowKeys: React.Key[]) => {
            if (!selectedRowKeys?.length || selectedRowKeys?.length > 1) {
                setSingle(true);
            } else {
                setSingle(false);
            }
            selectedRowKeys?.length ? setMultiple(false) : setMultiple(true);
            setSelectKeys(selectedRowKeys);
            setRowKeys(selectedRowKeys.join(','));
        },
    };
    // 查看本地离线数据
    const showLocalCheckData = async () => {
        if (!ipc) {
            return message.warn('只有在客户端才能执行此功能');
        }
        localCheckDataModalOpenSet(true);
        ipc
            .invoke(ipcApiRoute.lenodbOperation, {
                tableName: 'jiaoyanjieguo_table',
                action: 'getAll',
            })
            .then((res: any) => {
                // console.log(`res.result`, res.result);
                // res.result.forEach((item) => {
                //   item.jiaoyanjieguo = JSON.parse(item.jiaoyanjieguo);
                // });
                res.result.sort((prev: any, next: any) => {
                    const res = new Date(prev.created_at).getTime() - new Date(next.created_at).getTime();
                    return res > 0 ? -1 : 1;
                });
                hookThis.current.localCheckCom.tableDataSet(res.result);
                hookThis.current.localCheckCom.selectKeysSet([]);
            });
    };
    // 同步校验规则到本地
    // const syncDataFromServer = async () => {
    //     if (!ipc) {
    //         return message.warn('只有在客户端才能执行此功能');
    //     }
    //     syncDataFromServerLoadingSet(true)
    //     Promise.all([gongzuoleixingList(), jiaoyanguizeList(), shebeiList(), shebeifenzuList(), shebeileixingList()]).then((res: any) => {
    //         // 对应的表名
    //         // gongzuoleixing_table2
    //         // jiaoyanguize_table
    //         // shebei_table2
    //         // shebeifenzu_table
    //         // shebeileixing_table
    //         // leno_user,
    //         // sys_dept,
    //         Promise.all(res.map((data:any)=>{
    //           return ipc.invoke(ipcApiRoute.lenodbOperation, { action: 'batchAdd', batchAddParam: data.rows, tableName: data.tableName, Overlay: true }).then((res: any) => {});
    //         })).then(() => {
    //           message.success('同步成功');
    //           syncDataFromServerLoadingSet(false)
    //         })
    //     });
    // };

    const syncDataFromServer = async () => {
        if (!ipc) {
            return message.warn('只有在客户端才能执行此功能');
        }
        syncDataFromServerLoadingSet(true);
        
        try {
            Promise.all([gongzuoleixingList(), jiaoyanguizeList(), shebeiList(), shebeifenzuList(), shebeileixingList()]).then((res: any) => {
                const leno_admin:any = {}
                res.forEach((item:any) => {
                    leno_admin[item.tableName] = item.rows
                })
                downloadJSON(leno_admin, 'leno_admin');
                syncDataFromServerLoadingSet(false);
                message.success('同步成功');
            }); 
    
            // 将所有数据一次性写入数据库
            // await ipc.invoke(ipcApiRoute.lenodbOperation, { action: 'batchAdd', batchAddParam: allData, Overlay: true });
    
            // message.success('同步成功');
            // syncDataFromServerLoadingSet(false);
        } catch (error) {
            console.error('同步失败：', error);
            message.error('同步失败');
            syncDataFromServerLoadingSet(false);
        }
    };
    
    // 获取详情
    const handleEditForm = async (id: number, type?: string) => {
        try {
            const { data } = await getDetailAPI(id);
            setCurrentId(id);
            setIsModalOpen(true);
            setIsAdd(false);
            if (type === 'readonly') {
                data.result.readonly = true;
            } else {
                data.result.readonly = false;
            }
            data.result.jiaoyanjieguo = JSON.parse(data.result.jiaoyanjieguo as string);
            detailSet(data.result);
            addEditForm.setFieldsValue(data.result as unknown as IjiaoyantableDetailType);
        } catch (error) { }
    };

    // 表单提交
    const handleFormFinish = async (values?: IjiaoyantableDetailType) => {
        try {
            if (isAdd) {
                await addAPI({ ...values });
                message.success('新增成功');
            } else {
                // 触发修改接口就要把审核结果改成待审核
                detail.jiaoyanjieguo.checkPerson = userInfo.userName;
                const editParam = { jiaoyanjieguo: JSON.stringify(detail.jiaoyanjieguo), check_result: '0' };
                await putAPI({ ...editParam, tableId: currentId });
                message.success('修改成功');
            }
        } catch (error) { }
        setIsModalOpen(false);
        addEditForm.resetFields();
        getList();
    };

    // 分页
    const onPagChange = async (pageNum: number, pageSize: number) => {
        const form = queryForm.getFieldsValue();
        setQueryParams({ pageNum, pageSize, ...form });
    };
    // 删除
    const delFn = (ids: string) => {
        confirm({
            icon: <ExclamationCircleOutlined />,
            content: `是否确认删除？`,
            centered: true,
            async onOk() {
                try {
                    const { data } = await delAPI(ids);
                    message.success(data.message);
                    pageDelJump(dataList.count, ids, queryParams, setQueryParams);
                    searchQueryFn()
                } catch (error) { }
            },
        });
    };

    // table
    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            align: 'left',
            render: (text, record, index) => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1, // 渲染序号
        },
        {
            title: '名称',
            dataIndex: 'originalFilename',
            key: 'originalFilename',
            align: 'left',
        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            key: 'createdAt',
            align: 'left',
        },
        // {
        //   title: '校验码',
        //   dataIndex: 'newFilename',
        //   key: 'newFilename',
        //   align: 'left',
        // },

        {
            title: '校验结果',
            dataIndex: 'jiaoyanjieguo',
            key: 'jiaoyanjieguo',
            align: 'left',
            render: (_: any, record: IjiaoyantableDetailType) => {
                const jiaoyanjieguo = JSON.parse(record.jiaoyanjieguo as string);
                const flag = jiaoyanjieguo.checkStatus === '0';
                return (
                    <div>
                        {flag ? <span className="blue-color">通过</span> : <span className="red-color">不通过</span>}
                        {/* 不通过的才有站长审核 */}
                        {flag ? (
                            <span className="blue-color"></span>
                        ) : (
                            <Button type="link" onClick={() => handleEditForm(record.tableId as number)}>
                                站长审核
                            </Button>
                        )}
                    </div>
                );
            },
        },
        {
            title: '校验结果详情',
            dataIndex: 'jiaoyanjieguoxiangqing',
            key: 'jiaoyanjieguoxiangqing',
            align: 'left',
            render: (_: any, record: IjiaoyantableDetailType) => (
                <div>
                    <Button type="link" onClick={() => handleEditForm(record.tableId as number, 'readonly')}>
                        校验结果详情
                    </Button>
                </div>
            ),
        },
        {
            title: '审核结果',
            dataIndex: 'checkResult',
            key: 'checkResult',
            align: 'left',
            render: (_: any, record: IjiaoyantableDetailType) => {
                if (!record.checkResult) {
                    record.checkResult = '0';
                }
                // 0 待审核，1 自动审核通过，2 省长审核通过 3省长审核不通过
                const checkMap: IjiaoyantableShenHeType = {
                    '0': '待审核',
                    '1': '自动审核通过',
                    '2': '省长审核通过',
                    '3': '省长审核不通过',
                };
                return <div>{checkMap[record.checkResult as keyof IjiaoyantableShenHeType]}</div>;
            },
        },
        {
            title: '审核人',
            dataIndex: 'checkUserId',
            key: 'checkUserId',
            align: 'left',
            // render: (_: any, record: IjiaoyantableDetailType) => (
            //   <div>
            //     <Button type="link" onClick={() => handleEditForm(record.tableId as number, 'readonly')}>
            //       校验结果详情
            //     </Button>
            //   </div>
            // ),
        },
        {
            title: '操作',
            key: 'operation',
            align: 'left',
            fixed: 'right',
            render: (_: any, record: IjiaoyantableDetailType) => {
                if (!record.checkResult) {
                    record.checkResult = '0';
                }
                return (
                    <div>
                        <Button
                            onClick={() => {
                                checkResultRemarksSet('');
                                setCurrentId(record.tableId);
                                setcheckModalOpen(true);
                            }}
                            hidden={isZhanZhang || record.checkResult !== '0'}
                            size="small"
                            type="link"
                        >
                            省长审核
                        </Button>
                        <Button
                            onClick={() => {
                                setCurrentId(record.tableId);
                                setcheckModalOpen(true);
                            }}
                            hidden={!['2', '3'].includes(record.checkResult)}
                            size="small"
                            type="link"
                        >
                            查看审核详情
                        </Button>
                        <Button
                            // hidden={hasPermi('equipment:jiaoyantable:remove')}
                            hidden={isZhanZhang}
                            size="small"
                            // icon={<DeleteOutlined />}
                            type="link"
                            onClick={() => delFn(String(record.tableId))}
                        >
                            删除
                        </Button>                        
                    </div>
                );
            },
        },
    ] as ColumnsType<IjiaoyantableDetailType>;
    const columns2 = [
        {
            title: '参数',
            dataIndex: 'key',
            key: 'key',
            align: 'left',
            width: 200,
            ellipsis: true,
        },
        {
            title: '值',
            dataIndex: 'value',
            key: 'value',
            align: 'left',
            render: (_: any, record: any) => <span>{record.status === '1' ? <span className="red-color">{record.value}</span> : record.value}</span>,
            width: 150,
            ellipsis: true,
        },
        {
            title: '期望值',
            dataIndex: 'expected',
            key: 'expected',
            align: 'left',
            width: 150,
            ellipsis: true,
        },
        {
            title: '校验',
            dataIndex: 'status',
            key: 'status',
            align: 'left',
            render: (_: any, record: any) => <span>{record.status === '1' ? <span className="red-color">不通过</span> : '通过'}</span>,
            width: 100,
            ellipsis: true,
        },
        {
            title: '站长备注',
            dataIndex: 'remarks',
            key: 'remarks',
            align: 'left',
            render: (_: any, record: any) => (
                <div>
                    {detail.readonly || record.status === '0' ? (
                        <span>{record.remarks}</span>
                    ) : (
                        <Input
                            readOnly={detail.readonly}
                            style={{ width: 240 }}
                            placeholder="站长备注"
                            value={record.remarks}
                            allowClear
                            onChange={(e) => {
                                record.remarks = e.target.value;
                                detailSet({ ...detail });
                            }}
                        />
                    )}
                </div>
            ),
        },
    ];

    // table 数据源
    const tableData = dataList.rows;
    const currentRow = tableData.find((item: any) => item.tableId === currentId);
    const isChecked = currentRow?.checkResult !== '0';

    // 导出表格为CSV文件
    const exportToCSV = (allData: any) => {
        const mapResultToText: any = {
            '0': '通过',
            '1': '不通过',
        };
        const { newFilename, jiaoyanjieguo, originalFilename } = allData;

        const csvContent =
            `data:text/csv;charset=utf-8,` +
            `参数,值,期望值,校验结果,站长备注\n${jiaoyanjieguo.checkData.map((item: any) => `${item.key},${item.value},${item.expected},${mapResultToText[item.status]},${item.remarks}`).join('\n')}`;
        const encodedURI = encodeURI(csvContent);
        const link = document.createElement('a');
        link.setAttribute('href', encodedURI);
        link.setAttribute('download', `${originalFilename}_checked.csv`);
        document.body.appendChild(link);
        link.click();
    };

    return (
        <div className="app-container">
          <Spin spinning={syncDataFromServerLoading}  >
            {/* <div id='lixianshuju'>{JSON.stringify(lixianshuju)}</div> */}
            <Row gutter={16}>
                <Col span={24}>
                    <Form form={queryForm} hidden={!searchShow} layout="inline" className="leno-search">
                        <Form.Item label="站" name="deptId" rules={[{ required: true, message: '请选择站' }]}>
                            <Select
                                style={{ width: 240 }}
                                placeholder="站"
                                onChange={(v: any) => {
                                    deptIdSet(v);
                                    searchQueryFn();
                                }}
                                // allowClear
                                options={deptArr.map((item: any) => ({
                                    value: item?.deptId,
                                    label: item.deptName,
                                }))}
                            />
                        </Form.Item>
                        <Form.Item label="所属组名" name="groupName">
                            <ShebeifenzuTableSelect queryParams={{ deptId }} style={{ width: 240 }} placeholder="请选择所属组" allowClear onChange={searchQueryFn} />
                        </Form.Item>
                        <Form.Item label="文件名称" name="originalFilename">
                            <Input style={{ width: 240 }} placeholder="请输入文件名称" allowClear onPressEnter={searchQueryFn} />
                        </Form.Item>
                        <Form.Item label="上传时间" name="createTimeDuration">
                            <RangePicker showTime  style={{ width: 240 }} />
                        </Form.Item>
                        <Form.Item>
                            <Button onClick={searchQueryFn} type="primary" icon={<SearchOutlined />}>
                                搜索
                            </Button>
                        </Form.Item>
                        <Form.Item>
                            <Button onClick={resetQueryFn} icon={<SyncOutlined />}>
                                重置
                            </Button>
                        </Form.Item>
                        <Form.Item>
                            {isZhanZhang && <span>离线相关功能：</span>}
                            <Button loading={syncDataFromServerLoading} hidden={!isZhanZhang} onClick={syncDataFromServer}>
                                下载校验规则数据到客户端 <span className='bolder-color'> (约3分钟)</span>
                            </Button>
                        </Form.Item>
                        <Form.Item>
                            <Button hidden={!isZhanZhang} onClick={showLocalCheckData}>
                                查看客户端离线校验数据
                            </Button>
                        </Form.Item>

                        <Col></Col>
                    </Form>

                    <Row gutter={16} className='file-btn-line'>
                        {/* <Col span={2}>
                            <div className='file-title'>文件操作：</div>
                        </Col> */}
                        <Col >
                            <ColorBtn
                                type="primary"
                                hidden={!isZhanZhang}
                                className="sub-btn"
                                color="info"
                                // icon={<ToTopOutlined />}
                                onClick={() => {
                                    setIsUploadModalOpen(true);
                                }}
                            >
                                文件上传
                            </ColorBtn>
                        </Col>
                        <Col >
                            <ColorBtn
                                // hidden={hasPermi('equipment:jiaoyantable:export')}
                                // hidden={true}
                                // className="ml10"
                                icon={<VerticalAlignBottomOutlined />}
                                // url: string, fileName = 'excel', fileFormat = 'xlsx', params?: object
                                onClick={() => download('/equipment/jiaoyantable/export', '文件校验结果', 'xlsx', { ...queryParams })}
                            >
                                导出
                            </ColorBtn>
                        </Col>
                        <Col > 
                            <a className='downAllFiles' href="https://pic.rmb.bdstatic.com/baidu-rmb-video-cover-1/2024-4/1714136728740/9991a12a405c.zip">
                                下载鄱阳湖站全部初始文件
                            </a>
                        </Col>
                        <Col>
                        <ColorBtn
                            // hidden={hasPermi('equipment:jiaoyantable:remove')}
                            hidden={isZhanZhang}
                            onClick={() => delFn(rowKeys)}
                            disabled={multiple}
                            color="danger"
                            icon={<DeleteOutlined />}
                        >
                            删除
                        </ColorBtn>
                        </Col>                        
                    </Row>
                    <div className="leno-table">
                        <Table columns={columns} dataSource={tableData} pagination={false} rowKey="tableId" size="middle" loading={loading}   
                        rowSelection={!isZhanZhang ? { type: 'checkbox', fixed: 'left', ...rowSelection }:null}
                        />
                        <Pagination className="pagination" onChange={onPagChange} total={dataList.count} showSizeChanger showQuickJumper current={queryParams.pageNum} showTotal={(total) => `共 ${total} 条`} />
                    </div>

                    {/* 添加 编辑 */}
                    <Modal
                        title={'校验结果'}
                        width="1000px"
                        okText="站长审核通过"
                        open={isModalOpen}
                        footer={[
                            <span className="submit-notice">{detail.readonly ? '' : '站长点击确定后，当前校验结果行会将【审核结果】更变为【待审核】'}</span>,
                            <Button
                                key="submit"
                                type="primary"
                                onClick={() => {
                                    handleFormFinish();
                                }}
                                hidden={detail.readonly}
                            >
                                站长审核通过
                            </Button>,
                        ]}
                        onCancel={() => {
                            setIsModalOpen(false);

                            addEditForm.resetFields();
                        }}
                    >
                        <div >
                            {/* <div className="check-code">
                文件校验结果为：<span className="code-txt">{detail.checkResult === '1' ? '通过' : '不通过'}</span>
              </div> */}
                            <div className="check-reslut">数据校验结果：</div>
                            <Table
                                columns={columns2}
                                width="100%"
                                dataSource={detail.jiaoyanjieguo.checkData}
                                pagination={false}
                                rowKey="tableId"
                                size="middle"
                                scroll={{
                                    y: 500,
                                }}
                                rowClassName={(record) => (record.status === '1' ? 'errorRow' : 'okRow')}
                            // loading={loading}
                            //
                            />

                            <Button type="primary" className="btn-submit" onClick={() => exportToCSV(detail)}>
                                下载
                            </Button>
                        </div>

                        {/* <div style={{ width: '1000px' }}>
                <Form
                form={addEditForm}
                labelCol={{ span: 5 }}
                onFinish={handleFormFinish}
                >
                <Form.Item
                    label="校验结果"
                    name="jiaoyanjieguo"
                    rules={[{ max: 500, message: '请输入内容(500字以内)!' }]}
                >
                    <TextArea rows={20} showCount placeholder="请输入内容(200字以内)" />
                </Form.Item>

                </Form>
            </div> */}

                        {/* {
              JSON.parse(detail.jiaoyanjieguo).map((item:any) => item)
            } */}
                    </Modal>
                    <Modal title="用户导入" confirmLoading={uploadLoading} open={isUploadModalOpen} onOk={handleUploadOk} onCancel={handleUploadCancel}>
                        <div className="work-type">
                            工作类型：
                            <GongzuoleixingTable2Radios
                                value={workTypeValue}
                                onChange={(v: any) => {
                                    workTypeValueSet(v.target.value);
                                }}
                            ></GongzuoleixingTable2Radios>
                        </div>
                        <div className="upload-box" >
                            <Dragger {...props} height={200}>
                                <p className="ant-upload-drag-icon">
                                    <InboxOutlined />
                                </p>
                                <p className="ant-upload-text">将文件拖到此处，或点击上传</p>
                            </Dragger>                            
                        </div>
                        <Row justify="center" align="middle" style={{ fontSize: 12, color: '#808080' }}>
                            支持单文件、多文件上传
                        </Row>
                    </Modal>
                    <Modal
                        title="审核"
                        open={checkModalOpen}
                        onOk={handleCheckOk}
                        onCancel={handleCheckCancel}
                        footer={[
                            <Button
                                key="back"
                                onClick={() => {
                                    handleCheckOk('3');
                                }}
                                hidden={isChecked}
                            >
                                不通过
                            </Button>,
                            <Button
                                key="submit"
                                type="primary"
                                onClick={() => {
                                    handleCheckOk('2');
                                }}
                                hidden={isChecked}
                            >
                                审核通过
                            </Button>,
                        ]}
                    >
                        <TextArea
                            disabled={isChecked}
                            value={isChecked ? currentRow?.checkResultRemarks : checkResultRemarks}
                            onChange={(v) => {
                                checkResultRemarksSet(v.target.value);
                            }}
                            placeholder="请输入内容(200字以内)"
                        />
                        <div className='mt10'>
                            审核时间：{isChecked ? currentRow?.updatedAt : ''}
                        </div>
                    </Modal>
                    <Modal
                        title="本地校验结果"
                        open={localCheckDataModalOpen}
                        width={800}
                        onOk={() => { }}
                        onCancel={() => {
                            localCheckDataModalOpenSet(false);
                            getList();
                        }}
                        footer={[]}
                    >
                        <LocalCheckCom
                            onRender={(api: any) => {
                                hookThis.current.localCheckCom = api;
                            }}
                            refresh={() => {
                                showLocalCheckData();
                            }}
                        ></LocalCheckCom>
                    </Modal>
                </Col>
            </Row>
            </Spin>
        </div>
    );
};

export default JiaoyanjieguoTable;
